package com.ljwy.daka.okgoHelper;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import com.ljwy.daka.utils.ToastUtils;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.request.base.Request;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.SocketException;
import java.net.SocketTimeoutException;

import okhttp3.Response;

/**
 * Created by Sloop on 2018/8/21
 * Description:
 */
public abstract class JsonCallback<T> extends AbsCallback<T> {
    private Type type;
    private Class<T> clazz;
    private Context context;
    private boolean isShowLoading = true;
    private LoadingView loadingDialog;

    public JsonCallback() {
    }

    public JsonCallback(Type type) {
        this.type = type;
    }

    public JsonCallback(Class<T> clazz) {
        this.clazz = clazz;
    }

    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
    }

    public void setShowLoading(boolean showLoading) {
        isShowLoading = showLoading;
    }

    @Override
    public void onStart(Request<T, ? extends Request> request) {
        super.onStart(request);
//        UserInfo userInfo = ACacheHelper.getInstance().get().getAsObject(Constant.KEY_USER);
//        if (userInfo != null) {
//            request.headers("Authorization", userInfo.getToken());
//            Log.e("TOKEN", userInfo.getToken());
//        }
        if (isShowLoading) {
            showLoadingDialog();
        }
    }

    @Override
    public T convertResponse(Response response) throws Throwable {
        if (type == null) {
            if (clazz == null) {
                Type genType = getClass().getGenericSuperclass();
                //返回表示此类型实际类型参数的 Type 对象的数组
                type = ((ParameterizedType) genType).getActualTypeArguments()[0];
            } else {
                JsonConvert<T> convert = new JsonConvert<>(clazz);
                return convert.convertResponse(response);
            }
        }
        JsonConvert<T> convert = new JsonConvert<>(type);
        return convert.convertResponse(response);
    }

    @Override
    public void onFinish() {
        super.onFinish();
        if (isShowLoading) {
            closeLoadingDialog();
        }
    }

    @Override
    public void onCacheSuccess(com.lzy.okgo.model.Response<T> response) {
        super.onCacheSuccess(response);
    }

    @Override
    public void onError(com.lzy.okgo.model.Response<T> response) {
        super.onError(response);
        try {
            Log.d("httpOnError", response.getRawResponse().request().url().toString());
        } catch (Exception e) {
            Log.d("httpOnError", "response.getRawResponse().request().url().toString()---null");
        }
        int code = response.code();
        if (code == 404) {
            ToastUtils.showShort("无法连接服务器，请稍候再试");
        } else if (code == 500) {
            ToastUtils.showShort("服务器异常，请稍候再试");
        } else if (response.getException() instanceof SocketTimeoutException) {
            ToastUtils.showShort("网络链接超时，请稍候再试");
        } else if (response.getException() instanceof SocketException) {
            ToastUtils.showShort("服务器异常，请稍候再试");
        } else if (response.getException() instanceof MyException) {
           // BaseResponse errorBean = ((MyException) response.getException()).getErrorBean();

        } else {
            ToastUtils.showShort("网络异常，请稍候再试");
        }
    }

    private void showLoadingDialog() {
        if (loadingDialog == null) {
            loadingDialog = new LoadingView(context);
        }
        if (loadingDialog.isShowing()) {
            return;
        }
        if (context instanceof Activity) {
            if (!((Activity) context).isFinishing()) {
                try {
                    loadingDialog.show();
                } catch (Exception e) {
                    Log.e("ErrorError", e.toString());
                }
            }
        }
    }

    private void closeLoadingDialog() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
            loadingDialog = null;
        }
    }

}